import {
	BASE_URL
} from "@/config/index.js"
import {
	notLogged
} from "@/utils/tool.js"

function getToken() {
	return uni.getStorageSync("accessToken")
}

function setToken(token) {
	uni.setStorageSync('accessToken', token)
}

let requestQueue = [];
let isRefreshingToken = false; // 用于防止重复刷新token  
let refreshTokenPromise = null; // 缓存token刷新的Promise  

// 封装请求函数  
function request(url, options = {}) {
	return new Promise((resolve, reject) => {
		const token = getToken();
		if (token) {
			options.header = {
				// ... 其他头部信息  
				'Authorization': `Bearer ${token}`
			};
		}
		// 发起请求  
		uni.request({
			url: BASE_URL + url,
			...options,
			success: (res) => {
				console.log(res.data)
				// 从队列中移除请求  
				removeRequestFromQueue(url);
				resolve(res.data);
				if (res.data.code === 401) {
					uni.removeStorageSync('accessToken')
					notLogged()
					// uni.redirectTo({
					// 	url: "/pages/mine/index"
					// })
					// addToRequestQueue(url, options, resolve, reject);
					// // 尝试刷新token  
					// refreshToken().then(newToken => {
					// 	// 使用新token重试请求  
					// 	retryRequests();
					// }).catch(err => {
					// 	// 刷新token失败，拒绝所有等待的请求  
					// 	rejectAllRequestsInQueue(err);
					// });
				} else if (res.data.code !== 0) {
					uni.showToast({
						title: res.data.msg,
						icon: "none"
					})
				}
			},
			fail: (err) => {
				uni.hideLoading()
				console.log(err)
				if (err.errMsg === "request:fail timeout") {
					uni.showToast({
						title: "请求超时，请刷新后重试",
						icon: "none",
						mask: true,
						duration: 3000
					})
				} else {
					reject(err);
					uni.showToast({
						title: "请求服务器失败，请稍后重试",
						icon: "none",
						mask: true,
						duration: 3000
					})
				}

			}
		});
	});
}

// 添加到请求队列  
function addToRequestQueue(url, options, resolve, reject) {
	requestQueue.push({
		url,
		options,
		resolve,
		reject
	});
}

// 从请求队列中移除请求  
function removeRequestFromQueue(url) {
	requestQueue = requestQueue.filter(queuedReq => queuedReq.url !== url);
}

// 刷新token  
function refreshToken() {
	if (!isRefreshingToken) {
		isRefreshingToken = true;
		refreshTokenPromise = new Promise((resolve, reject) => {
			let refreshToken = uni.getStorageSync("refreshToken")
			// 发送刷新token的请求到后端  
			uni.request({
				url: BASE_URL + '/member/auth/refresh-token?refreshToken=' + refreshToken, // 刷新token的URL  
				method: 'POST', // 通常使用POST请求刷新token  
				success: (res) => {
					if (res.data.code === 400) {
						uni.clearStorageSync()
						return uni.reLaunch({
							url: "/pages/index/index"
						})
					}
					uni.setStorageSync('refreshToken', res.data.data.refreshToken)
					const newToken = res.data.data.accessToken; // 假设你得到了新的token  
					setToken(newToken); // 存储新的token  
					resolve(newToken);
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	}
	return refreshTokenPromise;
}

// 重试请求队列中的所有请求  
function retryRequests() {
	requestQueue.forEach(queuedReq => {
		// 使用新的token重新发起请求  
		request(queuedReq.url, queuedReq.options).then(data => {
			queuedReq.resolve(data);
		}).catch(err => {
			queuedReq.reject(err);
		});
		// 移除已重试的请求  
		removeRequestFromQueue(queuedReq.url);
	});
}

// 拒绝请求队列中的所有请求  
function rejectAllRequestsInQueue(err) {
	requestQueue.forEach(queuedReq => {
		queuedReq.reject(err);
	});
	// 清空队列  
	requestQueue = [];
}


export default request